package com.xxh.dasongapp.security.service.impl;

import com.xxh.dasongapp.common.entity.Role;
import com.xxh.dasongapp.common.entity.User;
import com.xxh.dasongapp.common.entity.UserRole;
import com.xxh.dasongapp.security.common.entity.LoginUser;
import com.xxh.dasongapp.security.service.UserOpenIdDetailsService;
import com.xxh.dasongapp.service.RoleService;
import com.xxh.dasongapp.service.UserRoleService;
import com.xxh.dasongapp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.List;


/**
 * 根基openid获取用户信息
 */
@Service
public class UserOpenIdDetailServiceImpl implements UserOpenIdDetailsService {

    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RoleService roleService;

    @Override
    public UserDetails loadUserByOpenId(String openId) throws UsernameNotFoundException {
        User user = userService.getByOpenId(openId);
        if (user == null){
            return null;
        }
        Assert.isTrue(user.getStatus()==1,"账号状态异常");
        UserRole userRole = userRoleService.getByUserId(user.getId());
        Role role = roleService.getByRoleId(userRole.getRoleId());

        //角色集合
        List<String> permissions = new ArrayList<>();
        permissions.add(role.getPermissionName());


        return new LoginUser(user,permissions);
    }
}
